package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.bo.LoginInfoSaveBO;
import com.yt.sys.models.bo.UserSaveBO;
import com.yt.sys.models.dto.LoginInfoDTO;
import com.yt.sys.models.service.ILoginInfoService;
import com.yt.sys.models.vo.AddAccountRequest;
import com.yt.sys.models.vo.AddUserAccountRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.IUserService;
import com.yt.sys.models.bo.UserBO;
import com.yt.sys.models.dto.UserDTO;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 客户信息控制器
 *
 * @author lizicong
 * @Date 2025-10-29 21:42:52
 */

@RestController
@RequestMapping("/api/user")
@Slf4j
@Api(value = "UserApiController",tags = "客户信息Api接口")
public class UserApiController {

    @DubboReference
    private IUserService userService;
    @Resource
    private ILoginInfoService loginInfoService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<UserDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        UserDTO dto = userService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "客户信息列表",notes = "客户信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<UserDTO>> queryPageList(UserBO bo){
        Wrapper<UserDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<UserDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = userService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    @ApiOperation(value = "添加客户信息",notes = "添加客户信息")
    @PostMapping(value = "/insert")
    public Result insert(@RequestBody UserSaveBO saveBO) {
        System.out.println("添加客户信息检测点");
        boolean flag = userService.add(saveBO);
        UserDTO dto = userService.selectOne(new EntityWrapper<UserDTO>().eq("user_phone", saveBO.getUserPhone()));
        System.out.println("添加客户信息返回结果："+dto.toString());
        AddUserAccountRequest request = new AddUserAccountRequest();
        //密码等于电话号码后六位
        request.setPassword(saveBO.getUserPhone().substring(saveBO.getUserPhone().length()-6));
        System.out.println("添加客户信息请求参数："+request.toString());
        LoginInfoSaveBO loginInfoSaveBO = new LoginInfoSaveBO();
        System.out.println(dto.getUserId());
        loginInfoSaveBO.setUserId(dto.getUserId());
        System.out.println(loginInfoSaveBO.getUserId());
        loginInfoSaveBO.setAccount(saveBO.getUserPhone());
        System.out.println("添加客户信息请求参数："+loginInfoSaveBO.toString());
        //检验账号是否存在
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account",request.getAccount());
        List<LoginInfoDTO> list = loginInfoService.selectList(wrapper);
        if(list!=null&&!list.isEmpty()){
            return new Result<>(CodeEnum.FAIL_100003.getCode(),"账号已存在");
        }
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        String encryptedPassword = DigestUtils.md5DigestAsHex((request.getPassword() + salt).getBytes());
        loginInfoSaveBO.setPassword(encryptedPassword);
        loginInfoSaveBO.setSalt(salt);
        loginInfoSaveBO.setStatus(1);
        boolean result = loginInfoService.add(loginInfoSaveBO);
        if (result) {
            return new Result<>(CodeEnum.SUCCESS.getCode(), "账号创建成功");
        }
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }
    @ApiOperation(value = "修改客户信息",notes = "修改客户信息")
    @PostMapping("/update")
    public Result update(@RequestBody UserSaveBO saveBO){
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setUserId(saveBO.getUserId());
        boolean flag = userService.updateById(dto);
        if (flag){
            return new Result<>();
        } else {

            return new Result<>(CodeEnum.FAIL_100008);
        }
    }
    @ApiOperation(value = "删除客户信息",notes = "删除客户信息")
    @ApiImplicitParam(name = "id",value = "虚拟电话号码信息id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        boolean flag = userService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }
    @ApiOperation(value = "获取客户信息列表",notes = "获取客户信息列表")
    @PostMapping("/list")
    public Result<List<UserDTO>> getuserList(){
        System.out.println("获取列表检测点");
        List<UserDTO> list = userService.getuserList();
        return new Result<>(list);
    }
    @ApiOperation(value = "获取客户信息分页列表", notes = "获取客户信息分页列表")
    @PostMapping("/pagelist/{page}")
    public Result<Map<String, Object>> getuserpage(@PathVariable("page") int page) {
        log.info("获取分页列表检测点，页码：{}", page);

        // 1. 调用 Service 获取分页数据
        Page<UserDTO> userDTOPage = userService.getpageuserList(page);

        // 2. 生成页码列表
        int pages = (int) userDTOPage.getPages();
        List<Integer> pageList = IntStream.rangeClosed(1, pages)
                .boxed()
                .collect(Collectors.toList());

        // 3. 用 Map 封装所有信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", userDTOPage.getRecords()); // 当前页数据
        resultMap.put("current", userDTOPage.getCurrent()); // 当前页码
        resultMap.put("size", userDTOPage.getSize()); // 每页条数
        resultMap.put("total", userDTOPage.getTotal()); // 总记录数
        resultMap.put("pages", pages); // 总页数
        resultMap.put("pageList", pageList); // 页码列表

        return new Result<>(resultMap);
    }

    @ApiOperation(value = "根据关键词获取客户信息列表",notes = "根据关键词获取客户信息列表-")
    @PostMapping("/search/{keyword}")
    public Result<List<UserDTO>> searchgetuserList(@PathVariable("keyword") String keyword){
        System.out.println("获取列表检测点");
        List<UserDTO> list = userService.searchgetuserList(keyword);
        return new Result<>(list);
    }
    @ApiOperation(value = "获取公客信息分页列表", notes = "获取公客信息分页列表")
    @PostMapping("/public/pagelist/{page}")
    public Result<Map<String, Object>> getpublicuserpage(@PathVariable("page") int page) {
        log.info("获取分页列表检测点，页码：{}", page);

        // 1. 调用 Service 获取分页数据
        Page<UserDTO> userDTOPage = userService.getpagepublicuserList(page);

        // 2. 生成页码列表
        int pages = (int) userDTOPage.getPages();
        List<Integer> pageList = IntStream.rangeClosed(1, pages)
                .boxed()
                .collect(Collectors.toList());

        // 3. 用 Map 封装所有信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", userDTOPage.getRecords()); // 当前页数据
        resultMap.put("current", userDTOPage.getCurrent()); // 当前页码
        resultMap.put("size", userDTOPage.getSize()); // 每页条数
        resultMap.put("total", userDTOPage.getTotal()); // 总记录数
        resultMap.put("pages", pages); // 总页数
        resultMap.put("pageList", pageList); // 页码列表

        return new Result<>(resultMap);
    }
    @ApiOperation(value = "获取商客信息分页列表", notes = "获取商客信息分页列表")
    @PostMapping("/business/pagelist/{page}")
    public Result<Map<String, Object>> getbusinessuserpage(@PathVariable("page") int page) {
        log.info("获取分页列表检测点，页码：{}", page);

        // 1. 调用 Service 获取分页数据
        Page<UserDTO> userDTOPage = userService.getpagebusinessuserList(page);

        // 2. 生成页码列表
        int pages = (int) userDTOPage.getPages();
        List<Integer> pageList = IntStream.rangeClosed(1, pages)
                .boxed()
                .collect(Collectors.toList());

        // 3. 用 Map 封装所有信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", userDTOPage.getRecords()); // 当前页数据
        resultMap.put("current", userDTOPage.getCurrent()); // 当前页码
        resultMap.put("size", userDTOPage.getSize()); // 每页条数
        resultMap.put("total", userDTOPage.getTotal()); // 总记录数
        resultMap.put("pages", pages); // 总页数
        resultMap.put("pageList", pageList); // 页码列表

        return new Result<>(resultMap);
    }
}
